package com.yunyao.framework.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yunyao.common.constant.enums.DataDeletedStatus;
import com.yunyao.common.dto.SpReconciliationDto;
import com.yunyao.common.dto.SpReconciliationOrderDto;
import com.yunyao.common.web.enums.ResultMsgEnum;
import com.yunyao.common.web.util.PageResult;
import com.yunyao.common.web.util.YResult;
import com.yunyao.dao.model.BamuPoSupply;
import com.yunyao.dao.model.BamuSpReconciliationOrder;
import com.yunyao.dao.model.BamuSpReconciliationOrderMaterial;
import com.yunyao.dao.service.bamu.IBamuPoSupplyService;
import com.yunyao.dao.service.bamu.IBamuSpReconciliationOrderMaterialService;
import com.yunyao.dao.service.bamu.IBamuSpReconciliationOrderService;
import com.yunyao.framework.dto.posyupply.PoSosyupplySaveDto;
import com.yunyao.framework.dto.spreconciliatioin.*;
import com.yunyao.framework.service.SpReconciliationOrderService;
import com.yunyao.framework.vo.spreconciliation.SpReconciliationMaterialCountVO;
import com.yunyao.framework.vo.spreconciliation.SpReconciliationMaterialVO;
import com.yunyao.framework.vo.spreconciliation.SpReconciliationOrderVO;
import com.yunyao.framework.vo.spreconciliation.SpReconciliationPoSupplyVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotBlank;
import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SpReconciliationOrderServiceImpl implements SpReconciliationOrderService {

    @Autowired
    private IBamuSpReconciliationOrderMaterialService iBamuSpReconciliationOrderMaterialService;
    @Autowired
    private IBamuPoSupplyService iBamuPoSupplyService;
    @Autowired
    private IBamuSpReconciliationOrderService iBamuSpReconciliationOrderService;

    @Override
    public YResult<PageResult<SpReconciliationMaterialVO>> getSpReconciliationMaterialList(SpReconciliationMaterialDto spReconciliationMaterialDto) {
//        // 构建查询条件
//        String contractId = spReconciliationMaterialDto.getContractId();
////        String orderSn = spReconciliationMaterialDto.getReconciliationOrderSn();
//        String purchaseApplyId = spReconciliationMaterialDto.getPurchaseApplyId();
//        LambdaQueryWrapper<BamuSpReconciliationOrderMaterial> wrapper = new LambdaQueryWrapper<BamuSpReconciliationOrderMaterial>()
//                .eq(BamuSpReconciliationOrderMaterial::getContractId, contractId)
////                .eq(BamuSpReconciliationOrderMaterial::getReconciliationOrderId, purchaseApplyId)
//                .eq(BamuSpReconciliationOrderMaterial::getIsDeleted, DataDeletedStatus.NO.getType());
        LambdaQueryWrapper<BamuSpReconciliationOrderMaterial> queryWrapper = new LambdaQueryWrapper<BamuSpReconciliationOrderMaterial>()
                .eq(BamuSpReconciliationOrderMaterial::getIsDeleted, DataDeletedStatus.NO.getType())
                .eq(BamuSpReconciliationOrderMaterial::getReconciliationId, spReconciliationMaterialDto.getReconciliationId())
                .orderByAsc(BamuSpReconciliationOrderMaterial::getMaterialSortNum);

        // 分页查询
        IPage<BamuSpReconciliationOrderMaterial> payPage = new Page<>(spReconciliationMaterialDto.getPageIndex(), spReconciliationMaterialDto.getPageSize());
        payPage = iBamuSpReconciliationOrderMaterialService.page(payPage, queryWrapper);

        // 处理查询结果
        if (CollectionUtils.isEmpty(payPage.getRecords())) {
            return YResult.success(new PageResult<>());
        }

        // 转换为VO对象列表
        List<SpReconciliationMaterialVO> materialVOList = materialDaoToVoList(payPage.getRecords());

        // 返回分页结果
        return YResult.success(new PageResult<>(materialVOList, payPage.getCurrent(), payPage.getSize(), payPage.getPages(), payPage.getTotal()));

    }


    @Override
    public BigDecimal getBySupplyIdHistorySum(String bizId) {

        List<BamuSpReconciliationOrderMaterial> list = iBamuSpReconciliationOrderMaterialService.lambdaQuery()
                .eq(BamuSpReconciliationOrderMaterial::getReconciliationId, bizId)
                .eq(BamuSpReconciliationOrderMaterial::getIsDeleted, DataDeletedStatus.NO.getType())
                .list();
        if (CollectionUtils.isEmpty(list)) {
            return BigDecimal.ZERO;
        }
        return list
                .stream()
                .map(BamuSpReconciliationOrderMaterial::getIncludingTaxTotalPrice)
                .reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
    }


    private List<SpReconciliationMaterialVO> materialDaoToVoList(List<BamuSpReconciliationOrderMaterial> records) {
        return records.stream().map(this::materialDaoToVo).collect(Collectors.toList());
    }

    private SpReconciliationMaterialVO materialDaoToVo(BamuSpReconciliationOrderMaterial bamuSpReconciliationOrderMaterial) {
        SpReconciliationMaterialVO spReconciliationMaterialVO = new SpReconciliationMaterialVO();
        BeanUtils.copyProperties(bamuSpReconciliationOrderMaterial, spReconciliationMaterialVO);
        spReconciliationMaterialVO.setOrderSn(bamuSpReconciliationOrderMaterial.getReconciliationOrderId());
        return spReconciliationMaterialVO;
    }


    @Override
    public YResult<String> saveMaterialInfo(SpReconciliationMaterialSaveDto saveDto) {
        List<SpReconciliationMaterialInfoSaveDto> dtoList = saveDto.getSaveDtoList();
        if (CollectionUtils.isEmpty(dtoList)) {
            return YResult.error(ResultMsgEnum.PARAM_ERROR);
        }
        List<BamuSpReconciliationOrderMaterial> daoList = materialDtoToDaoList(dtoList);
        if (CollectionUtils.isEmpty(daoList)) {
            return YResult.error(ResultMsgEnum.PARAM_ERROR);
        }
        iBamuSpReconciliationOrderMaterialService.saveOrUpdateBatch(daoList, 20);
        return YResult.success(saveDto.getContractId());
    }

    private List<BamuSpReconciliationOrderMaterial> materialDtoToDaoList(List<SpReconciliationMaterialInfoSaveDto> dtoList) {
        return dtoList.stream().map(this::materialDtoToDao).collect(Collectors.toList());
    }

    private BamuSpReconciliationOrderMaterial materialDtoToDao(SpReconciliationMaterialInfoSaveDto SpReconciliationMaterialInfoSaveDto) {
        BamuSpReconciliationOrderMaterial bamuSpReconciliationOrderMaterial = new BamuSpReconciliationOrderMaterial();
        BeanUtils.copyProperties(SpReconciliationMaterialInfoSaveDto, bamuSpReconciliationOrderMaterial);
        return bamuSpReconciliationOrderMaterial;
    }

    @Override
    public YResult<String> deletedMaterialInfo(SpReconciliationMaterialDeleteDto deletedDto) {
        if (CollectionUtils.isEmpty(deletedDto.getIdList())) {
            return YResult.error(ResultMsgEnum.PARAM_ERROR);
        }
        List<BamuSpReconciliationOrderMaterial> updateList = Lists.newArrayList();
        for (String id : deletedDto.getIdList()) {
            BamuSpReconciliationOrderMaterial bamuSpReconciliationOrderMaterial = new BamuSpReconciliationOrderMaterial();
            bamuSpReconciliationOrderMaterial.setId(id);
            bamuSpReconciliationOrderMaterial.setIsDeleted(DataDeletedStatus.YES.getType());
            updateList.add(bamuSpReconciliationOrderMaterial);
        }
        iBamuSpReconciliationOrderMaterialService.updateBatchById(updateList, 20);
        return YResult.success(deletedDto.getContractId());
    }

    @Override
    public YResult<PageResult<SpReconciliationPoSupplyVO>> getSpReconciliationPoSupplyList(SpReconciliationPoSupplyDto spReconciliationPoSupplyDto) {
        // 构建查询条件
        String contractId = spReconciliationPoSupplyDto.getContractId();
//        String orderSn = spReconciliationPoSupplyDto.getOrderSn();
        LambdaQueryWrapper<BamuPoSupply> wrapper = new LambdaQueryWrapper<BamuPoSupply>()
                .eq(BamuPoSupply::getContractId, contractId)
//                .eq(BamuPoSupply::getOrderSn, orderSn)
                .eq(BamuPoSupply::getIsDeleted, DataDeletedStatus.NO.getType())
                .eq(BamuPoSupply::getReconciliationStatus, 0);
        // 分页查询
        IPage<BamuPoSupply> payPage = new Page<>(spReconciliationPoSupplyDto.getPageIndex(), spReconciliationPoSupplyDto.getPageSize());
        payPage = iBamuPoSupplyService.page(payPage, wrapper);

        // 处理查询结果
        if (CollectionUtils.isEmpty(payPage.getRecords())) {
            return YResult.success(new PageResult<>());
        }

        // 转换为VO对象列表
        List<SpReconciliationPoSupplyVO> posupplyVOList = posupplyDaoToVoList(payPage.getRecords());

        // 返回分页结果
        return YResult.success(new PageResult<>(posupplyVOList, payPage.getCurrent(), payPage.getSize(), payPage.getPages(), payPage.getTotal()));

    }

    @Override
    public YResult<PageResult<SpReconciliationOrderVO>> getSpReconciliationPoSupplyList(SpReconciliationOrderDto spReconciliationOrderDto) {
        LambdaQueryWrapper<BamuSpReconciliationOrder> queryWrapper =
                new LambdaQueryWrapper<BamuSpReconciliationOrder>()
                        .eq(BamuSpReconciliationOrder::getIsDeleted, DataDeletedStatus.NO.getType())
                        .eq(BamuSpReconciliationOrder::getReconciliationId, spReconciliationOrderDto.getReconciliationId())
                        .orderByAsc(BamuSpReconciliationOrder::getId);
        // 分页查询
        IPage<BamuSpReconciliationOrder> settlementPage = new Page<>(spReconciliationOrderDto.getPageIndex(), spReconciliationOrderDto.getPageSize());
        settlementPage = iBamuSpReconciliationOrderService.page(settlementPage, queryWrapper);

        // 处理查询结果
        if (CollectionUtils.isEmpty(settlementPage.getRecords())) {
            return YResult.success(new PageResult<>());
        }

        // 转换为VO对象列表
        List<SpReconciliationOrderVO> voList = orderDaoToVoList(settlementPage.getRecords());

        // 返回分页结果
        return YResult.success(new PageResult<>(voList, settlementPage.getCurrent(),
                settlementPage.getSize(), settlementPage.getPages(), settlementPage.getTotal()));
    }


    /**
     * 供应商-根据合同id查询对账中的验收清单id
     *
     * @param contractId
     * @return
     */
    @Override
    public List<String> getSoSupply(@NotBlank String contractId) {
        List<BamuSpReconciliationOrder> list = iBamuSpReconciliationOrderService.lambdaQuery()
                .eq(BamuSpReconciliationOrder::getContractId, contractId)
                .eq(BamuSpReconciliationOrder::getIsDeleted, DataDeletedStatus.NO.getType())
                .list();
        if (CollectionUtils.isNotEmpty(list)) {
            return list.stream()
                    .map(BamuSpReconciliationOrder::getId)
                    .collect(Collectors.toList());
        }
        return null;
    }

    private List<SpReconciliationOrderVO> orderDaoToVoList(List<BamuSpReconciliationOrder> records) {
        return records.stream().map(this::orderDaoToVo).collect(Collectors.toList());
    }

    private SpReconciliationOrderVO orderDaoToVo(BamuSpReconciliationOrder bamuSpReconciliationOrder) {
        SpReconciliationOrderVO reconciliationOrderVO = new SpReconciliationOrderVO();
        BeanUtils.copyProperties(bamuSpReconciliationOrder, reconciliationOrderVO);
        return reconciliationOrderVO;
    }


    private List<BamuPoSupply> posupplyDtoToDaoList(List<PoSosyupplySaveDto> dtoList) {
        return dtoList.stream().map(this::posupplyDtoToDao).collect(Collectors.toList());
    }

    private BamuPoSupply posupplyDtoToDao(PoSosyupplySaveDto soSupplyDto) {
        BamuPoSupply bamuPoSupply = new BamuPoSupply();
        BeanUtils.copyProperties(soSupplyDto, bamuPoSupply);
        return bamuPoSupply;
    }

    private List<SpReconciliationPoSupplyVO> posupplyDaoToVoList(List<BamuPoSupply> records) {
        return records.stream().map(this::posupplyDaoToVo).collect(Collectors.toList());
    }

    private SpReconciliationPoSupplyVO posupplyDaoToVo(BamuPoSupply bamuPoSupply) {
        SpReconciliationPoSupplyVO spReconciliationPoSupplyVO = new SpReconciliationPoSupplyVO();
        BeanUtils.copyProperties(bamuPoSupply, spReconciliationPoSupplyVO);
        return spReconciliationPoSupplyVO;
    }

    @Override
    public YResult<String> savePoSupplyInfo(SpReconciliationPoSupplySaveDto saveDto) {
        List<PoSosyupplySaveDto> dtoList = saveDto.getSaveDtoList();
        if (CollectionUtils.isEmpty(dtoList)) {
            return YResult.error(ResultMsgEnum.PARAM_ERROR);
        }
        List<BamuPoSupply> daoList = posupplyDtoToDaoList(dtoList);
        if (CollectionUtils.isEmpty(daoList)) {
            return YResult.error(ResultMsgEnum.PARAM_ERROR);
        }
        iBamuPoSupplyService.saveOrUpdateBatch(daoList, 20);
        return YResult.success(saveDto.getContractId());
    }

    @Override
    public YResult<String> deletedPoPupplyInfo(SpReconciliationPoSupplyDeletedDto deletedDto) {
        if (CollectionUtils.isEmpty(deletedDto.getIdList())) {
            return YResult.error(ResultMsgEnum.PARAM_ERROR);
        }
        List<BamuPoSupply> updateList = Lists.newArrayList();
        for (String id : deletedDto.getIdList()) {
            BamuPoSupply bamuPoSupply = new BamuPoSupply();
            bamuPoSupply.setId(id);
            bamuPoSupply.setIsDeleted(DataDeletedStatus.YES.getType());
            updateList.add(bamuPoSupply);
        }
        iBamuPoSupplyService.updateBatchById(updateList, 20);
        return YResult.success(deletedDto.getContractId());
    }

    @Override
    public YResult<SpReconciliationMaterialCountVO> getSpReconciliationMaterialCount(SpReconciliationDto spReconciliationDto) {
        try {
            // 提取合同ID
            String reconciliationId = spReconciliationDto.getId();
            // 校验合同ID是否为空
            if (StringUtils.isBlank(reconciliationId)) {
                return YResult.error(ResultMsgEnum.PARAM_ERROR);
            }
            // 更新合同材料数量（具体实现略）
//            updateContractMaterialCount(contractId);
            // 初始化合同材料计数对象
            SpReconciliationMaterialCountVO spReconciliationMaterialCountVO = new SpReconciliationMaterialCountVO();
            // 获取合同材料总数
//            BigDecimal countSupplyNum = iBamuSpReconciliationOrderMaterialService.getSupplyNumByContractId(reconciliationId);
//            // 获取合同材料总价格
//            BigDecimal countComfirmSupplyNum = iBamuSpReconciliationOrderMaterialService.getComfirmSupplyNumByContractId(contractId);
//            BigDecimal countIncludingTaxtotalPrice = iBamuSpReconciliationOrderMaterialService.getIncludingTaxTotalPriceByContractId(contractId);
//            BigDecimal countReconciliationPrice = iBamuSpReconciliationOrderMaterialService.getReconciliationPriceByContractId(contractId);
//            // 设置总数和总价格到VO对象
//            spReconciliationMaterialCountVO.setCountSupplyNum(countSupplyNum);
//            spReconciliationMaterialCountVO.setCountComfirmSupplyNum(countComfirmSupplyNum);
//            spReconciliationMaterialCountVO.setCountIncludingTaxtotalPrice(countIncludingTaxtotalPrice);
//            spReconciliationMaterialCountVO.setCountReconciliationPrice(countReconciliationPrice);
//            // 返回成功结果
//            return YResult.success(spReconciliationMaterialCountVO);
            // 获取合同材料总数
            BigDecimal countSupplyNum = iBamuSpReconciliationOrderMaterialService.getSupplyNumByContractId(reconciliationId);
            if (countSupplyNum != null) {
                spReconciliationMaterialCountVO.setCountSupplyNum(countSupplyNum);
            } else {
                spReconciliationMaterialCountVO.setCountSupplyNum(null);
            }

// 获取合同材料总价格（这里假设是已确认的供应量，但变量名可能有些误导）
            BigDecimal countComfirmSupplyNum = iBamuSpReconciliationOrderMaterialService.getComfirmSupplyNumByContractId(reconciliationId);
            if (countComfirmSupplyNum != null) {
                spReconciliationMaterialCountVO.setCountComfirmSupplyNum(countComfirmSupplyNum);
            } else {
                spReconciliationMaterialCountVO.setCountComfirmSupplyNum(null);
            }

// 获取合同材料总价格（包含税）
            BigDecimal countIncludingTaxtotalPrice = iBamuSpReconciliationOrderMaterialService.getIncludingTaxTotalPriceByContractId(reconciliationId);
            if (countIncludingTaxtotalPrice != null) {
                spReconciliationMaterialCountVO.setCountIncludingTaxtotalPrice(countIncludingTaxtotalPrice);
            } else {
                spReconciliationMaterialCountVO.setCountIncludingTaxtotalPrice(null);
            }

// 获取合同材料对账价格
            BigDecimal countReconciliationPrice = iBamuSpReconciliationOrderMaterialService.getReconciliationPriceByContractId(reconciliationId);
            if (countReconciliationPrice != null) {
                spReconciliationMaterialCountVO.setCountReconciliationPrice(countReconciliationPrice);
            } else {
                spReconciliationMaterialCountVO.setCountReconciliationPrice(null);
            }

// 返回成功结果，即使某些值为null，VO对象仍会包含已设置的值
            return YResult.success(spReconciliationMaterialCountVO);
        } catch (Exception ex) {
            // 捕获异常，返回系统错误信息
            return YResult.success(new SpReconciliationMaterialCountVO());
        }
    }
}
